from flask import Blueprint, render_template, request, jsonify, redirect, url_for, flash, abort
from flask_login import login_required, current_user
from functools import wraps
import logging
from werkzeug.security import generate_password_hash
from datetime import datetime

from app.models.db import get_db
from app.utils.log_config import get_logger

user_bp = Blueprint('user', __name__)
logger = get_logger('user')

# 管理员权限装饰器
def admin_required(f):
    @wraps(f)
    @login_required
    def decorated_function(*args, **kwargs):
        if not current_user.is_authenticated:
            logger.warning('未认证用户尝试访问管理员页面')
            return redirect(url_for('auth.login_page'))
        
        if current_user.role != 'admin':
            logger.warning(f'非管理员用户 {current_user.username} 尝试访问管理员页面')
            abort(403)  # 使用HTTP 403禁止访问状态码
        
        return f(*args, **kwargs)
    return decorated_function

# 用户管理页面
@user_bp.route('/user/management')
@admin_required
def user_management_page():
    return render_template('user_management.html')

# 获取用户列表（API）
@user_bp.route('/api/users', methods=['GET'])
@admin_required
def get_users():
    try:
        cursor = get_db().cursor()
        cursor.execute("SELECT id, username, role, created_at, last_login FROM user")
        users = cursor.fetchall()
        
        # 转换为字典列表
        user_list = []
        for user in users:
            user_list.append({
                'id': user[0],
                'username': user[1],
                'role': user[2],
                'created_at': user[3],
                'last_login': user[4]
            })
        
        return jsonify({'status': 'success', 'data': user_list})
    except Exception as e:
        logger.error(f'获取用户列表失败: {str(e)}')
        return jsonify({'status': 'error', 'message': '获取用户列表失败'})

# 添加新用户（API）
@user_bp.route('/api/users', methods=['POST'])
@admin_required
def add_user():
    try:
        data = request.get_json()
        
        # 参数验证
        if not data:
            return jsonify({'status': 'error', 'message': '请求体不能为空'}), 400
            
        username = data.get('username')
        password = data.get('password')
        role = data.get('role', 'operator')
        
        # 检查必要字段
        if not username or not password:
            return jsonify({'status': 'error', 'message': '用户名和密码不能为空'}), 400
        
        # 验证角色值
        if role not in ['admin', 'operator']:
            return jsonify({'status': 'error', 'message': '无效的角色值'}), 400
        
        db = get_db()
        cursor = db.cursor()
        try:
            # 检查用户名是否重复
            cursor.execute("SELECT * FROM user WHERE username=?", (data['username'],))
            if cursor.fetchone():
                return jsonify({'status': 'error', 'message': '用户名已存在'}), 409
            
            # 加密密码并插入用户
            hashed_password = generate_password_hash(data['password'])
            cursor.execute('''
            INSERT INTO user (username, password, role, created_at)
            VALUES (?, ?, ?, ?)
            ''', (
                data['username'],
                hashed_password,
                data['role'],
                datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            ))
            db.commit()
            logger.info(f'管理员 {current_user.username} 创建新用户: {username}')
            return jsonify({'status': 'success', 'message': '用户添加成功'})
        except Exception as db_error:
            db.rollback()
            logger.error(f'添加用户数据库操作失败: {str(db_error)}')
            return jsonify({'status': 'error', 'message': '添加用户失败'}), 500
    except Exception as e:
        logger.error(f'添加用户失败: {str(e)}')
        return jsonify({'status': 'error', 'message': '添加用户失败'}), 500

# 编辑用户（API）
@user_bp.route('/api/users/<int:user_id>', methods=['PUT'])
@admin_required
def update_user(user_id):
    try:
        data = request.get_json()
        
        if not data:
            return jsonify({'status': 'error', 'message': '请求体不能为空'}), 400
            
        # 获取用户信息
        db = get_db()
        cursor = db.cursor()
        cursor.execute("SELECT * FROM user WHERE id=?", (user_id,))
        user = cursor.fetchone()
        if not user:
            return jsonify({'status': 'error', 'message': '用户不存在'}), 404
        
        # 不允许修改当前登录用户的角色
        if user_id == current_user.id and 'role' in data:
            return jsonify({'status': 'error', 'message': '不能修改当前登录用户的角色'}), 403
        
        try:
            # 检查用户名是否重复（排除自身）
            if 'username' in data:
                cursor.execute("""
                SELECT * FROM user 
                WHERE username=? AND id != ?
                """, (data['username'], user_id))
                if cursor.fetchone():
                    return jsonify({'status': 'error', 'message': '用户名已存在'}), 400
            
            # 构建更新语句（支持修改密码或不修改）
            if data.get('password'):
                # 需修改密码
                hashed_password = generate_password_hash(data['password'])
                if 'role' in data and 'username' in data:
                    # 验证角色值
                    if data['role'] not in ['admin', 'operator']:
                        return jsonify({'status': 'error', 'message': '无效的角色值'}), 400
                    cursor.execute('''
                    UPDATE user SET username=?, role=?, password=? WHERE id=?
                    ''', (data['username'], data['role'], hashed_password, user_id))
                elif 'username' in data:
                    cursor.execute('''
                    UPDATE user SET username=?, password=? WHERE id=?
                    ''', (data['username'], hashed_password, user_id))
                elif 'role' in data:
                    # 验证角色值
                    if data['role'] not in ['admin', 'operator']:
                        return jsonify({'status': 'error', 'message': '无效的角色值'}), 400
                    cursor.execute('''
                    UPDATE user SET role=?, password=? WHERE id=?
                    ''', (data['role'], hashed_password, user_id))
                else:
                    cursor.execute('''
                    UPDATE user SET password=? WHERE id=?
                    ''', (hashed_password, user_id))
            else:
                # 不修改密码
                if 'role' in data and 'username' in data:
                    # 验证角色值
                    if data['role'] not in ['admin', 'operator']:
                        return jsonify({'status': 'error', 'message': '无效的角色值'}), 400
                    cursor.execute('''
                    UPDATE user SET username=?, role=? WHERE id=?
                    ''', (data['username'], data['role'], user_id))
                elif 'username' in data:
                    cursor.execute('''
                    UPDATE user SET username=? WHERE id=?
                    ''', (data['username'], user_id))
                elif 'role' in data:
                    # 验证角色值
                    if data['role'] not in ['admin', 'operator']:
                        return jsonify({'status': 'error', 'message': '无效的角色值'}), 400
                    cursor.execute('''
                    UPDATE user SET role=? WHERE id=?
                    ''', (data['role'], user_id))
                else:
                    return jsonify({'status': 'error', 'message': '未提供要更新的字段'}), 400
            
            db.commit()
            logger.info(f'管理员 {current_user.username} 更新用户ID: {user_id}')
            return jsonify({'status': 'success', 'message': '用户更新成功'})
        except Exception as db_error:
            db.rollback()
            logger.error(f'更新用户数据库操作失败: {str(db_error)}')
            return jsonify({'status': 'error', 'message': '更新用户失败'}), 500
    except Exception as e:
        logger.error(f'更新用户失败: {str(e)}')
        return jsonify({'status': 'error', 'message': '更新用户失败'}), 500

# 删除用户（API）
@user_bp.route('/api/users/<int:user_id>', methods=['DELETE'])
@admin_required
def delete_user(user_id):
    try:
        # 不能删除当前登录的用户
        if user_id == current_user.id:
            return jsonify({'status': 'error', 'message': '不能删除当前登录的用户'}), 403
        
        # 检查用户是否存在
        db = get_db()
        cursor = db.cursor()
        cursor.execute("SELECT username FROM user WHERE id=?", (user_id,))
        user = cursor.fetchone()
        if not user:
            return jsonify({'status': 'error', 'message': '用户不存在'}), 404
        
        username = user[0]
        
        try:
            cursor.execute("DELETE FROM user WHERE id=?", (user_id,))
            db.commit()
            
            logger.info(f'管理员 {current_user.username} 删除用户: {username}')
            return jsonify({'status': 'success', 'message': '用户删除成功'})
        except Exception as db_error:
            db.rollback()
            logger.error(f'删除用户数据库操作失败: {str(db_error)}')
            return jsonify({'status': 'error', 'message': '删除用户失败'}), 500
    except Exception as e:
        logger.error(f'删除用户失败: {str(e)}')
        return jsonify({'status': 'error', 'message': '删除用户失败'}), 500